package com.beijing.syn;

/**
 * @Author Ma Wenqi
 * @Date 2021/3/27 16:59
 * @Version 1.0
 */

//不安全的
//线程不安全 有负数
public class UnsafeBuyTicket  implements  Runnable{
    //票数
    private int ticketNums = 10;
    boolean flag = true;  //外部停止方法

    @Override
    public void run() {
        while(flag){
            buy();
        }
    }


    //帮助线程同步：synchronized
    public synchronized void  buy(){
        //判断是否有票
        if(ticketNums<=0){
            flag = false;
            return;
        }
        //模拟延时
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"-->拿到了第"+ticketNums-- +"票");
    }

    public static void main(String[] args) {
        UnsafeBuyTicket ticket = new UnsafeBuyTicket();

        new Thread(ticket,"小明").start();
        new Thread(ticket,"老师").start();
        new Thread(ticket,"黄牛").start();
    }

}
